<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Video Background Transparency</title>
    <style>
        video, canvas {
            display: block;
            margin: 0 auto;
            width: 640px;
            height: 480px;
        }
    </style>
</head>
<body>

<!-- 指定视频源，替换成你自己的视频 URL -->
<video id="video" width="640" height="480" autoplay loop muted>
    <source src="assets/video/9999.mp4" type="video/mp4">
    Your browser does not support the video tag.
</video>

<!-- 用于绘制透明背景的 Canvas -->
<canvas id="canvas" width="640" height="480"></canvas>

<script>
    const video = document.getElementById('video');
    const canvas = document.getElementById('canvas');
    const ctx = canvas.getContext('2d');

    // 加载视频
    video.addEventListener('loadeddata', () => {
        // 在视频加载完成后开始处理帧
        requestAnimationFrame(processFrame);
    });

    // 绿色背景颜色的阈值范围 (用于 Chroma Key)
    const greenLowerBound = { r: 0, g: 100, b: 0 };
    const greenUpperBound = { r: 120, g: 255, b: 120 };

    // 判断像素是否为绿色背景
    function isGreen(r, g, b) {
        return (r >= greenLowerBound.r && r <= greenUpperBound.r) &&
            (g >= greenLowerBound.g && g <= greenUpperBound.g) &&
            (b >= greenLowerBound.b && b <= greenUpperBound.b);
    }

    // 处理每帧图像
    function processFrame() {
        // 将视频帧绘制到 Canvas 上
        ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
        const frame = ctx.getImageData(0, 0, canvas.width, canvas.height);
        const length = frame.data.length;

        // 遍历每个像素，检测并处理绿色背景
        for (let i = 0; i < length; i += 4) {
            const r = frame.data[i];
            const g = frame.data[i + 1];
            const b = frame.data[i + 2];

            if (isGreen(r, g, b)) {
                // 将背景像素透明化
                frame.data[i + 3] = 0;
            }
        }

        // 将处理过的图像重新绘制到 Canvas
        ctx.putImageData(frame, 0, 0);
        requestAnimationFrame(processFrame); // 下一帧继续处理
    }
</script>

</body>
</html>
